package com.example.medicalapp.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.medicalapp.R;
import com.example.medicalapp.helper.DatabaseHelper;
import com.example.medicalapp.model.Appointment;
import com.example.medicalapp.model.Prescription;
import com.example.medicalapp.network.DeepSeekService;
import com.example.medicalapp.util.PreferencesUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class PatientDetailActivity extends AppCompatActivity {
    private static final String TAG = "PatientDetailActivity";
    private static final int REQUEST_CAMERA_PERMISSION = 101;
    private static final int REQUEST_CAMERA = 102;
    private static final int REQUEST_GALLERY = 103;

    private TextView tvPatientName;
    private TextView tvIdCard;
    private TextView tvAppointTime;
    private EditText etSymptoms;
    private TextView tvAiProcess;
    private EditText etAiResult;
    private EditText etFinalPrescription;
    private Button btnTakePhoto;
    private Button btnSelectPhoto;
    private Button btnAiDiagnose;
    private Button btnSendPrescription;

    private DatabaseHelper dbHelper;
    private PreferencesUtil preferencesUtil;
    private DeepSeekService deepSeekService;
    private int appointmentId;
    private int patientId;
    private String patientName;
    private int doctorId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_detail);
        Log.d(TAG, "onCreate called");

        // 初始化视图
        initViews();

        // 初始化服务和工具类
        dbHelper = new DatabaseHelper(this);
        preferencesUtil = new PreferencesUtil(this);
        deepSeekService = new DeepSeekService(this);

        // 获取当前登录医生ID
        doctorId = preferencesUtil.getUserId();
        Log.d(TAG, "Current doctor ID: " + doctorId);

        // 获取从上一个页面传递的患者和预约信息
        getIntentData();

        // 加载患者详细信息
        loadPatientDetails();

        // 设置按钮点击事件
        setupButtonListeners();
    }

    private void initViews() {
        tvPatientName = findViewById(R.id.tv_patient_name);
        tvIdCard = findViewById(R.id.tv_id_card);
        tvAppointTime = findViewById(R.id.tv_appoint_time);
        etSymptoms = findViewById(R.id.et_symptoms);
        tvAiProcess = findViewById(R.id.tv_ai_process);
        etAiResult = findViewById(R.id.et_ai_result);
        etFinalPrescription = findViewById(R.id.et_final_prescription);
        btnTakePhoto = findViewById(R.id.btn_take_photo);
        btnSelectPhoto = findViewById(R.id.btn_select_photo);
        btnAiDiagnose = findViewById(R.id.btn_ai_diagnose);
        btnSendPrescription = findViewById(R.id.btn_send_prescription);
    }

    private void getIntentData() {
        // 获取患者和预约信息
        appointmentId = getIntent().getIntExtra(DoctorDepartmentActivity.EXTRA_APPOINTMENT_ID, -1);
        patientId = getIntent().getIntExtra(DoctorDepartmentActivity.EXTRA_PATIENT_ID, -1);
        patientName = getIntent().getStringExtra(DoctorDepartmentActivity.EXTRA_PATIENT_NAME);

        if (appointmentId == -1 || patientId == -1 || patientName == null) {
            Log.e(TAG, "Invalid patient or appointment data received");
            finish();
            return;
        }

        Log.d(TAG, "Received appointment ID: " + appointmentId + ", patient ID: " + patientId);
    }

    private void loadPatientDetails() {
        // 从数据库获取预约详情
        Appointment appointment = dbHelper.getAppointmentById(appointmentId);
        if (appointment != null) {
            tvPatientName.setText("姓名：" + appointment.getPatientName());
            tvIdCard.setText("身份证号：" + appointment.getIdCard());
            tvAppointTime.setText("预约时间：" + appointment.getAppointTime());
        } else {
            Log.e(TAG, "Appointment not found with ID: " + appointmentId);
            finish();
        }
    }

    private void setupButtonListeners() {
        // 拍照按钮点击事件
        btnTakePhoto.setOnClickListener(v -> checkCameraPermission());

        // 从相册选择按钮点击事件
        btnSelectPhoto.setOnClickListener(v -> openGallery());

        // AI辅助诊断按钮点击事件
        btnAiDiagnose.setOnClickListener(v -> startAiDiagnosis());

        // 发送处方按钮点击事件
        btnSendPrescription.setOnClickListener(v -> sendPrescription());
    }

    /**
     * 检查相机权限
     */
    private void checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA_PERMISSION);
        } else {
            openCamera();
        }
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
        Log.d(TAG, "Camera opened");
    }

    /**
     * 打开相册
     */
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_GALLERY);
        Log.d(TAG, "Gallery opened");
    }

    /**
     * 开始AI诊断
     */
    private void startAiDiagnosis() {
        Log.d(TAG, "Starting AI diagnosis with DeepSeek API");
        String symptoms = etSymptoms.getText().toString().trim();

        if (symptoms.isEmpty()) {
            Toast.makeText(this, "请先输入患者病情描述", Toast.LENGTH_SHORT).show();
            return;
        }

        // 网络检查：在此处调用，确保API请求前验证网络
        if (!isNetworkAvailable()) {
            Toast.makeText(this, "网络不可用，请检查网络连接", Toast.LENGTH_SHORT).show();
            return;
        }

        tvAiProcess.setText("");
        etAiResult.setText("");
        tvAiProcess.setText("AI分析中...");

        // 调用DeepSeek API进行诊断
        deepSeekService.sendDiagnosisRequest(symptoms);
    }

    /**
     * 更新AI诊断过程的UI显示
     */
    public void updateAiProcess(String newContent) {
        String currentText = tvAiProcess.getText().toString();
        // 如果是初始状态，先清除"AI分析中..."
        if (currentText.equals("AI分析中...")) {
            currentText = "";
        }
        tvAiProcess.setText(currentText + newContent);
        etAiResult.setText(currentText + newContent);
    }

    /**
     * AI诊断完成时调用
     */
    public void onAiDiagnosisComplete() {
        Log.d(TAG, "AI diagnosis completed");
        // 可以在这里添加完成后的操作，如显示提示信息等
    }

    /**
     * 检查网络是否可用
     */
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    /**
     * 发送处方
     */
    private void sendPrescription() {
        String symptoms = etSymptoms.getText().toString().trim();
        String aiAnalysis = etAiResult.getText().toString().trim();
        String finalPrescription = etFinalPrescription.getText().toString().trim();

        // 验证输入
        if (finalPrescription.isEmpty()) {
            Toast.makeText(this, "请输入最终诊断结果和处方", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取当前时间作为创建日期
        String currentDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                .format(new Date());

        // 创建处方对象
        Prescription prescription = new Prescription();
        prescription.setAppointmentId(appointmentId);
        prescription.setPatientId(patientId);
        prescription.setDoctorId(doctorId);
        prescription.setAiAnalysis(aiAnalysis);
        prescription.setFinalDiagnosis(symptoms);
        prescription.setFinalPrescription(finalPrescription);
        prescription.setCreatedDate(currentDate);

        // 保存到处方表
        long prescriptionId = dbHelper.insertPrescription(prescription);

        if (prescriptionId != -1) {
            Log.d(TAG, "Prescription saved with ID: " + prescriptionId);

            // 更新预约状态为已完成
            int rowsAffected = dbHelper.updateAppointmentStatus(appointmentId, "completed");
            if (rowsAffected > 0) {
                Log.d(TAG, "Appointment " + appointmentId + " status updated to completed");

                // 显示成功提示
                new AlertDialog.Builder(this)
                        .setTitle("成功")
                        .setMessage("处方已成功发送")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 返回科室患者列表页面
                            finish();
                        })
                        .setCancelable(false)
                        .show();
            } else {
                Log.e(TAG, "Failed to update appointment status");
                Toast.makeText(this, "保存处方失败，请重试", Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.e(TAG, "Failed to save prescription");
            Toast.makeText(this, "保存处方失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera();
            } else {
                Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 这里可以处理拍照和相册选择的结果
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                Log.d(TAG, "Photo taken successfully");
                // 处理相机返回的照片
                Toast.makeText(this, "照片拍摄成功", Toast.LENGTH_SHORT).show();
            } else if (requestCode == REQUEST_GALLERY) {
                Log.d(TAG, "Photo selected from gallery");
                // 处理相册返回的照片
                Toast.makeText(this, "照片选择成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭数据库连接
        if (dbHelper != null) {
            dbHelper.close();
        }
        Log.d(TAG, "onDestroy called");
    }
}
